﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Data;

public partial class SendEmail : System.Web.UI.Page
{
    PIMService services = new PIMService();
    private string type = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        string recipeid = "";
        if (Request.QueryString["recipeid"] != null)
            recipeid = Request.QueryString["recipeid"].ToString();
        if (Request.QueryString["type"] != null)
            type = Request.QueryString["type"].ToString();
        string AddIngredientname = "";
        if (Request.QueryString["AddIngredient"] != null)
            AddIngredientname = Request.QueryString["AddIngredient"].ToString();
        string removeingredient = "";
        if (Request.QueryString["rmingr"] != null)
            removeingredient = Request.QueryString["rmingr"].ToString();

        if (!string.IsNullOrEmpty(recipeid))
        {
            string[] _recipeid = recipeid.Split(',');
            DataTable _dt = services.getIngredientNameByRecipeIdList(recipeid);
            if (_dt != null && _dt.Rows.Count > 0)
            {
                string _recipename = "";
                string _IngredientName = "";
                int _index = 0;
                _recipename += "<p><b>INGREDIENT LIST OF RECIPE (";
                foreach (string str in _recipeid)
                {
                    _index++;
                    if (!string.IsNullOrEmpty(str) && str != "," )
                    {
                        DataRow[] dr = _dt.Select(string.Format("RecipeID={0}",str));
                        if (dr != null)
                        {
                            if (_index == _recipeid.Count())
                            {
                                _recipename += dr[0]["RecipeName"].ToString().ToUpper();
                            }
                            else
                                _recipename += dr[0]["RecipeName"].ToString().ToUpper() + ", ";
                            foreach (DataRow r in dr)
                            {
                                _IngredientName = _IngredientName + r["IngredientName"].ToString()+"+";
                            }
                        }
                    }
                }
                _recipename += ")</b></p><hr/>";
                string body = "";
                List<PIM.API.IngredientDept> lstIngredientDept = services.getIngredientDept(_IngredientName);
                if (lstIngredientDept != null && lstIngredientDept.Count() > 0)
                {
                    body += _recipename;
                    foreach (PIM.API.IngredientDept Depart in lstIngredientDept)
                    {
                        body += "<div class='emailtitle' style='width:auto;'>&nbsp;&nbsp;<h3>" + Depart.GroDept + "</h3></div>";

                        List<PIM.API.IngredientDeptDetail> lstIngredientDetail = services.getIngredientDeptDetail(_IngredientName, Depart.GroDept);
                        if (lstIngredientDetail != null && lstIngredientDetail.Count() > 0)
                        {
                            foreach (PIM.API.IngredientDeptDetail Detail in lstIngredientDetail)
                            {
                                if (CheckIngredientRemove(Detail.ingre, removeingredient.Split('|')) == 0)
                                {
                                    body += "<div class='emaildetail' >&nbsp;&nbsp;" + Detail.ingre + "</div>";
                                }
                                else
                                {
                                    body += "<div class='emaildetail' style='text-decoration:line-through;color:#D6D4D2'>&nbsp;&nbsp;" + Detail.ingre + "</div>";
                                }
                            }
                        }
                        body += "</br><hr/>";
                    }
                }

                if (!string.IsNullOrEmpty(AddIngredientname))
                {
                    string[] addingre = AddIngredientname.Split(',');
                    body += "<div class='emailtitle' style='width:auto;'>&nbsp;&nbsp;<h3>Additional</h3></div>";
                    foreach (string ingre in addingre)
                    {
                        if (!string.IsNullOrEmpty(ingre))
                        {
                            if (CheckIngredientRemove(ingre, removeingredient.Split('|')) == 0)
                            {
                                body += "<div class='emaildetail' >&nbsp;&nbsp;" + ingre + "</div>";
                            }
                            else
                            {
                                body += "<div class='emaildetail' style='text-decoration:line-through;color:#D6D4D2'>&nbsp;&nbsp;" + ingre + "</div>";
                            }
                        }
                    }
                    body += "</br><hr/>";
                }

                lblBody.Text = body;
            }
        }
    }

    public int CheckIngredientRemove(string ingredient, string[] listIngredient)
    {
        int rs = 0;
        foreach (string ingre in listIngredient)
        {
            if (ingredient == ingre)
            {
                rs = 1;
                break;
            }
        }
        return rs;
    }

    /*
    private void bindBody(string _recipeidArray)
    {
        string body = "";
        string _ingredientname = "";
        string _recipename = "";
        string[] _recipeid = _recipeidArray.Split(',');
        if (_recipeid.Count() > 0)
        {
            int _index = 0;
            _recipename += "<p><b>INGREDIENT LIST OF RECIPE (";
            foreach (string recipe in _recipeid)
            {
                _index++;
                if (!string.IsNullOrEmpty(recipe) || recipe != ",")
                {
                    List<PIM.API.RecipeIngredientUser> lst = new List<PIM.API.RecipeIngredientUser>();
                    lst = services.getRecipeIngredientUserByRecipeID(recipe);
                    if (lst != null && lst.Count() > 0)
                    {
                        if (_index == _recipeid.Count())
                            _recipename += lst[0].RecipeName.ToUpper();
                        else
                            _recipename += lst[0].RecipeName.ToUpper()+", ";
                        foreach (PIM.API.RecipeIngredientUser recipeIngerdient in lst)
                        {
                            if (!string.IsNullOrEmpty(body))
                                _ingredientname += recipeIngerdient.IngredientName;
                            else
                                _ingredientname += "+" + recipeIngerdient.IngredientName;
                            
                        }

                    }
                }
            }
            _recipename += ")</b></p><hr/>";

            if (!string.IsNullOrEmpty(_ingredientname))
            {
                body += "<html>";
                body += "<head>";
                body += "<title>www.planitmeal.com</title>";
                body += "</head>";
                body += "<body class='emaildetail'>";
                List<PIM.API.IngredientDept> lstIngredientDept = services.getIngredientDept(_ingredientname);
                if (lstIngredientDept!=null && lstIngredientDept.Count()>0)
                {
                    body += _recipename;
                    foreach (PIM.API.IngredientDept Depart in lstIngredientDept)
                    {
                        body += "<div class='emaildetail' style='width:auto;'>";
                        body += "&nbsp;&nbsp;<a><h3>" + Depart.GroDept + "</h3></a>";
                        body += "</div>";
                        List<PIM.API.IngredientDeptDetail> lstIngredientDetail = services.getIngredientDeptDetail(_ingredientname,Depart.GroDept);
                        if (lstIngredientDetail != null && lstIngredientDetail.Count() > 0)
                        {
                            foreach (PIM.API.IngredientDeptDetail Detail in lstIngredientDetail)
                            {
                                body += "<div class='emaildetail' >";
                                body += "&nbsp;&nbsp;<p >" + Detail.ingre + "</p>";
                                body += "</div>";
                            }
                        }
                        body += "</br><hr/>";
                    }
                }
                body += "</body>";
                body += "</html>";
                lblBody.Text = body;
            }
            
        }
    }
     */
    protected void btnSendMail_Click(object sender, EventArgs e)
    {
        SendMail(lblBody.Text);
    }

    private void SendMail(string _content)
    {
        try
        {
            if (!string.IsNullOrEmpty(txtEmail.Text))
            {
                string _userName = "";
                if (Session["UserName"] != null)
                    _userName = "of " + Session["UserName"].ToString();
                string _mailServer = "smtp.gmail.com";
                int _mailPort = 587;
                string _user = "planitmeal2013@gmail.com";
                string _pass = "11911431121176";
                string _mailFrom = "planitmeal2013@gmail.com";


                MailMessage mailMessage = new MailMessage();
                SmtpClient mailClient = new SmtpClient(_mailServer, _mailPort);
                mailClient.Timeout = 15000;
                mailClient.Credentials = new NetworkCredential(_user, _pass);
                mailClient.EnableSsl = true;

                mailMessage.IsBodyHtml = true;
                mailMessage.From = new MailAddress(_mailFrom);
                mailMessage.Subject = "[PlanItMeal]Grocery " + _userName;
                mailMessage.Body = _content;

                mailMessage.To.Add(txtEmail.Text);
                mailClient.Send(mailMessage);
                //att.Dispose();
                mailMessage.Dispose();

                ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Success", "alert('Email is sent, please check your email to view detail!')", true);
                Response.Write("<script type=\"text/javascript\">window.close();</script>");
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Please input email address!')", true);

            }
        }
        catch (Exception ex) { ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('" + ex.Message+ "!')", true); }
    }
    protected void btnCallBack_Click(object sender, ImageClickEventArgs e)
    {
        Response.Write("<script type=\"text/javascript\">window.close();</script>");
        //switch (type)
        //{
        //    case"1":
        //        Response.Redirect("AllRecipes.aspx");
        //        break;
        //    case "2":
        //        Response.Redirect("MyRecipes.aspx");
        //        break;
        //    case "3":
        //        Response.Redirect("AllMealPlans.aspx");
        //        break;
        //    case "4":
        //        Response.Redirect("MyMealPlans.aspx");
        //        break;
        //    default:
        //        break;
        //}
    }
}